package org.amphiprion.whohavethekids;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TreeMap;

import org.amphiprion.kidcalendar.dao.xml.ConfigurationDao;
import org.amphiprion.kidcalendar.entity.Configuration;
import org.amphiprion.kidcalendar.entity.Kid;
import org.amphiprion.kidcalendar.entity.Period;
import org.amphiprion.kidcalendar.entity.Period.PeriodType;
import org.amphiprion.kidcalendar.tool.NextPeriodPresence;
import org.amphiprion.kidcalendar.tool.NextVacationPresence;
import org.amphiprion.kidcalendar.tool.NextWeekendPresence;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.RemoteViews;

public class NextPresenceWidget extends AppWidgetProvider {
	private static SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy");

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

		final int N = appWidgetIds.length;

		// Perform this loop procedure for each App Widget that belongs to this
		// provider
		for (int i = 0; i < N; i++) {
			int appWidgetId = appWidgetIds[i];
			updateAppWidget(context, appWidgetManager, appWidgetId);
		}
	}

	@Override
	public void onDeleted(Context context, int[] appWidgetIds) {
		super.onDeleted(context, appWidgetIds);
		SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
		Editor editor = sharedPreferences.edit();
		for (int appWidgetId : appWidgetIds) {
			editor.remove("WIDGET_TYPE_INDEX_FOR_" + appWidgetId);
		}
		editor.commit();
	}

	/**
	 * Update the widget
	 * 
	 * @param context
	 * @param appWidgetManager
	 * @param appWidgetId
	 */
	static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {

		SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
		int widgetTypeIndex = sharedPreferences.getInt("WIDGET_TYPE_INDEX_FOR_" + appWidgetId, 0);
		int nbDatePerKid = sharedPreferences.getInt("WIDGET_NB_DATE_FOR_" + appWidgetId, 1);
		switch (widgetTypeIndex) {
		case 0:
			updateWeekendAppWidget(context, appWidgetManager, appWidgetId, nbDatePerKid);
			break;
		case 1:
			updateVacationAppWidget(context, appWidgetManager, appWidgetId, nbDatePerKid);
			break;
		case 2:
			updatePeriodAppWidget(context, appWidgetManager, appWidgetId, nbDatePerKid);
			break;
		}
	}

	static void updateVacationAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId, int nbDatePerKid) {

		Configuration c = ConfigurationDao.getInstance().getConfiguration();

		TreeMap<Period, String> kidsPerPeriod = new TreeMap<Period, String>();
		ArrayList<Kid> currentKid = new ArrayList<Kid>();
		for (Kid kid : c.getKids()) {
			currentKid.clear();
			currentKid.add(kid);
			Period p = null;
			for (int i = 0; i < nbDatePerKid; i++) {

				if (i == 0) {
					p = NextVacationPresence.getFirstPresence(currentKid);
				} else {
					GregorianCalendar startDate = new GregorianCalendar();
					startDate.setTime(p.getTo());
					startDate.add(Calendar.DAY_OF_YEAR, 1);
					p = NextVacationPresence.getFirstPresence(currentKid, startDate);
				}
				if (p != null) {
					String existingKids = kidsPerPeriod.get(p);
					if (existingKids == null) {
						existingKids = kid.getName();
					} else {
						existingKids += ", " + kid.getName();
					}
					kidsPerPeriod.put(p, existingKids);
				} else {
					break;
				}
			}
		}

		// RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.period_widget_layout);
		// views.removeAllViews(R.id.ListOfInfo);
		// for (Period p : kidsPerPeriod.keySet()) {
		// RemoteViews dateViews = new RemoteViews(context.getPackageName(), R.layout.widget_line_vacation);
		// dateViews.setTextViewText(R.id.txtDate, dateFormat.format(p.getFrom()) + " (" + p.getNumberOfDays() + ")");
		// // views.addView(R.id.ListOfInfo, dateViews);
		//
		// // RemoteViews txtViews = new RemoteViews(context.getPackageName(), R.layout.widget_text_layout);
		// dateViews.setTextViewText(R.id.txtName, kidsPerPeriod.get(p));
		//
		// dateViews.setImageViewResource(R.id.imgPeriod, R.drawable.vacation);
		// views.addView(R.id.ListOfInfo, dateViews);
		//
		// }
		//
		// Intent queryIntent = new Intent(context, QueryActivity.class);
		// queryIntent.setAction("org.amphiprion.whohavethekids.action.DISPLAY_QUERY");
		// PendingIntent queryPendingIntent = PendingIntent.getActivity(context, 1, queryIntent, PendingIntent.FLAG_UPDATE_CURRENT);
		// views.setOnClickPendingIntent(R.id.period_widget, queryPendingIntent);
		//
		// views.setViewVisibility(R.id.txtInit, View.GONE);
		// appWidgetManager.updateAppWidget(appWidgetId, views);

		updateAppWidgetContent(context, appWidgetManager, appWidgetId, kidsPerPeriod);

	}

	static void updateWeekendAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId, int nbDatePerKid) {

		Configuration c = ConfigurationDao.getInstance().getConfiguration();

		TreeMap<Period, String> kidsPerPeriod = new TreeMap<Period, String>();
		// List<Period> orderedPeriod = new Arra
		ArrayList<Kid> currentKid = new ArrayList<Kid>();
		for (Kid kid : c.getKids()) {
			currentKid.clear();
			currentKid.add(kid);
			Period p = null;
			for (int i = 0; i < nbDatePerKid; i++) {

				if (i == 0) {
					p = NextWeekendPresence.getFirstPresence(currentKid);
				} else {
					GregorianCalendar startDate = new GregorianCalendar();
					startDate.setTime(p.getTo());
					startDate.add(Calendar.DAY_OF_YEAR, 1);
					// System.out.println("CHECK " + i + " #### " + startDate.getTime());

					p = NextWeekendPresence.getFirstPresence(currentKid, startDate);

					// System.out.println("        Response=" + p);
				}
				if (p != null) {
					String existingKids = kidsPerPeriod.get(p);
					if (existingKids == null) {
						existingKids = kid.getName();
					} else {
						existingKids += ", " + kid.getName();
					}
					kidsPerPeriod.put(p, existingKids);
				} else {
					break;
				}
			}
		}

		// // Prepare widget views
		// RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.period_widget_layout);
		// views.removeAllViews(R.id.ListOfInfo);
		// for (Period p : kidsPerPeriod.keySet()) {
		// RemoteViews dateViews = new RemoteViews(context.getPackageName(), R.layout.widget_line_vacation);
		// dateViews.setTextViewText(R.id.txtDate, dateFormat.format(p.getFrom()) + " (" + p.getNumberOfDays() + ")");
		// // views.addView(R.id.ListOfInfo, dateViews);
		//
		// // RemoteViews txtViews = new RemoteViews(context.getPackageName(), R.layout.widget_text_layout);
		// dateViews.setTextViewText(R.id.txtName, kidsPerPeriod.get(p));
		//
		// dateViews.setImageViewResource(R.id.imgPeriod, R.drawable.weekend);
		// views.addView(R.id.ListOfInfo, dateViews);
		// }
		//
		// Intent queryIntent = new Intent(context, QueryActivity.class);
		// queryIntent.setAction("org.amphiprion.whohavethekids.action.DISPLAY_QUERY");
		// PendingIntent queryPendingIntent = PendingIntent.getActivity(context, 1, queryIntent, PendingIntent.FLAG_UPDATE_CURRENT);
		// views.setOnClickPendingIntent(R.id.period_widget, queryPendingIntent);
		//
		// views.setViewVisibility(R.id.txtInit, View.GONE);
		// appWidgetManager.updateAppWidget(appWidgetId, views);

		updateAppWidgetContent(context, appWidgetManager, appWidgetId, kidsPerPeriod);
	}

	static void updatePeriodAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId, int nbDatePerKid) {

		Configuration c = ConfigurationDao.getInstance().getConfiguration();

		TreeMap<Period, String> kidsPerPeriod = new TreeMap<Period, String>();
		// List<Period> orderedPeriod = new Arra
		ArrayList<Kid> currentKid = new ArrayList<Kid>();
		for (Kid kid : c.getKids()) {
			currentKid.clear();
			currentKid.add(kid);
			Period p = null;
			for (int i = 0; i < nbDatePerKid; i++) {

				if (i == 0) {
					p = NextPeriodPresence.getFirstPresence(currentKid);
				} else {
					GregorianCalendar startDate = new GregorianCalendar();
					startDate.setTime(p.getTo());
					startDate.add(Calendar.DAY_OF_YEAR, 1);
					// System.out.println("CHECK " + i + " #### " + startDate.getTime());

					p = NextPeriodPresence.getFirstPresence(currentKid, startDate);

					// System.out.println("        Response=" + p);
				}
				if (p != null) {
					System.out.println(kid.getName());
					p.debug();
					String existingKids = kidsPerPeriod.get(p);
					if (existingKids == null) {
						existingKids = kid.getName();
					} else {
						existingKids += ", " + kid.getName();
					}
					kidsPerPeriod.put(p, existingKids);
				} else {
					break;
				}
			}
		}

		updateAppWidgetContent(context, appWidgetManager, appWidgetId, kidsPerPeriod);
	}

	static void updateAppWidgetContent(Context context, AppWidgetManager appWidgetManager, int appWidgetId, TreeMap<Period, String> kidsPerPeriod) {
		// Prepare widget views
		RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.period_widget_layout);
		views.removeAllViews(R.id.ListOfInfo);
		for (Period p : kidsPerPeriod.keySet()) {
			RemoteViews dateViews = new RemoteViews(context.getPackageName(), R.layout.widget_line_vacation);
			dateViews.setTextViewText(R.id.txtDate, dateFormat.format(p.getFrom()) + " -> " + dateFormat.format(p.getTo()) + " (" + p.getNumberOfDays() + ")");
			// views.addView(R.id.ListOfInfo, dateViews);

			// RemoteViews txtViews = new RemoteViews(context.getPackageName(), R.layout.widget_text_layout);
			dateViews.setTextViewText(R.id.txtName, kidsPerPeriod.get(p));

			if (p.getType() == PeriodType.VACATION) {
				dateViews.setImageViewResource(R.id.imgPeriod, R.drawable.vacation);
			} else if (p.getType() == PeriodType.WEEKEND) {
				dateViews.setImageViewResource(R.id.imgPeriod, R.drawable.weekend);
			} else {
				dateViews.setImageViewResource(R.id.imgPeriod, R.drawable.period);
			}
			views.addView(R.id.ListOfInfo, dateViews);
		}

		Intent queryIntent = new Intent(context, QueryActivity.class);
		queryIntent.setAction("org.amphiprion.whohavethekids.action.DISPLAY_QUERY");
		PendingIntent queryPendingIntent = PendingIntent.getActivity(context, 1, queryIntent, PendingIntent.FLAG_UPDATE_CURRENT);
		views.setOnClickPendingIntent(R.id.period_widget, queryPendingIntent);

		views.setViewVisibility(R.id.txtInit, View.GONE);
		appWidgetManager.updateAppWidget(appWidgetId, views);
	}

}
